﻿namespace EasyWeb.Web.UI
{
    using System.Web.Mvc;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;

    public class EWTextModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = default(EWText);

            var json = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
            if (!string.IsNullOrEmpty(json))
            {
                model = new EWText();
                var array = JArray.Parse(json);
                foreach (var token in array)
                {
                    model.Values.Add(new EWTextValue((string)token["Name"], (string)token["Text"]));
                }
            }

            return model;
        }

        public static string ToJson(EWText text)
        {
            string json = null;

            if (text != null)
            {
                var array = new JArray();

                foreach (var value in text.Values)
                {
                    var obj = new JObject();
                    obj["Name"] = value.Name;
                    obj["Text"] = value.Text;

                    array.Add(obj);
                }

                json = array.ToString(Formatting.None);
            }

            return json;
        }
    }
}
